package com.sparrow.socket.util;

import com.google.common.base.Preconditions;
import com.sparrow.common.util.PackageUtil;
import com.sparrow.socket.anno.Packet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PacketHelper {

    private static final Logger log = LoggerFactory.getLogger(PacketHelper.class);
    private static Map<Integer, Class<?>> packetMap = new HashMap<>();

    /**
     * 注册消息协议路径
     * @param packageStr
     */
    public static void init(String packageStr) {
        Set<String> set = PackageUtil.scanClassNames(packageStr);
        for (String className: set) {
            Class<?> clazz;
            try {
                clazz = Class.forName(className);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            Packet annotation = clazz.getAnnotation(Packet.class);
            if (annotation == null) {
                continue;
            }
            int msgId = annotation.msgId();
            Class<?> pre = packetMap.put(msgId, clazz);
            Preconditions.checkState(pre == null, "消息id:" + msgId + " 冲突! pre:" + pre + " cur:" + clazz);
            CodecUtil.getCodec(clazz);
//            log.info("注册消息:{}", msgId);
        }
    }

    public static Class<?> getClass(int msgId) {
        return packetMap.get(msgId);
    }

}
